package multiclock

import (
	"blockchain/public/entity"
	"blockchain/public/function"
	"encoding/json"
	"fmt"
)

type pre_prepareMessage struct {
	tradeSet[TradeSize] entity.Trade
	priSeq int
	clientSign string
}

func pre_prepare(priSeq int)(pre_prepareMessage)  {
	request:=<-chanPriRecRequest[priSeq]
	flagreq[priSeq]<-true
	data,_:=json.Marshal(request.tradeSet)
	res:=function.VerifySign(data,request.sign,request.clientSeq)
	var pre_prepare pre_prepareMessage
	if res{
		pre_prepare.tradeSet=request.tradeSet
		pre_prepare.priSeq=priSeq
		pre_prepare.clientSign=request.sign
		return pre_prepare
	}else {
		fmt.Printf("主节点%d：发现客户%d，消息签名不一致\n",priSeq,request.clientSeq)
		return pre_prepare
	}

}


func pre_prepare1(priSeq int)(pre_prepareMessage)  {
	request:=<-chanPriRecRequest2[priSeq]
	flagreq1[priSeq]<-true
	data,_:=json.Marshal(request.tradeSet)
	res:=function.VerifySign(data,request.sign,request.clientSeq)
	var pre_prepare pre_prepareMessage
	if res{
		pre_prepare.tradeSet=request.tradeSet
		pre_prepare.priSeq=priSeq
		pre_prepare.clientSign=request.sign
		return pre_prepare
	}else {
		fmt.Printf("主节点%d：发现客户%d，消息签名不一致\n",priSeq,request.clientSeq)
		return pre_prepare
	}

}

func sendPre_prepareToNode(flagPre_prepared chan bool,pre_prepare pre_prepareMessage,priSeq int){
	for i:=0;i<N;i++{
		select {
		case chanNodeRecPre_prepare[i]<-pre_prepare:
			FlagPre_prepared[priSeq][i]<-true
			close(FlagPre_prepared[priSeq][i])
		default:
			FlagPre_prepared[priSeq][i]<-true
			close(FlagPre_prepared[priSeq][i])
		}
	}
	flagPre_prepared<-true
	close(flagPre_prepared)
}
